﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Net.Fan.SmallPig.Common.DBMeta;
using Net.Fan.SmallPig.DataAccess;
using Net.Fan.SmallPig.BusinessRules;

public partial class Job_JobModify : System.Web.UI.Page
{
    long jobId;
    protected void Page_Load(object sender, EventArgs e)
    {
        string js = Request.Params["J"];
        js = js.Trim();
        long.TryParse(js, out jobId);

        if (IsPostBack == false)
        {

            DataRow job = JobDA.GetJob(jobId);
            long workflowId = (long)job[JobMeta.WorkflowIDField];

            initControls(workflowId);
            LabelJobId.Text = js;
            HyperLinkDetail.NavigateUrl = string.Format("Job.aspx?J={0}", js);
            TextBoxSummary.Text = job[JobMeta.SummaryField] as string;
            TextBoxCount.Text = job[JobMeta.CountField].ToString();
            DropDownListUnit.SelectedValue = job[JobMeta.UnitField].ToString();
            TextBoxDesc.Text = job[JobMeta.DescriptionField] as string;

            LabelWorkflowId.Text = workflowId.ToString();
            DropDownListState.SelectedValue = job[JobMeta.CurrentStateField] as string; ;
            LabelWorkflowName.Text = WorkflowDA.GetWorkflowName(workflowId);
            object o = job[JobMeta.PlanFinishTimeField];
            if (o == null)
            {
            }
            else
            {
                TextBoxPlanFinishTime.Text = ((DateTime)o).ToString("yyyy-MM-dd");
            }

        }
    }

    private void initControls(long workflowId)
    {
        List<string> units = SystemSettingBiz.GetUnits();
        foreach (var item in units)
        {
            DropDownListUnit.Items.Add(item);
        }

        string[] states = WorkflowDA.GetAllCurrentStates(workflowId);
        foreach (var item in states)
        {
            DropDownListState.Items.Add(item);
        }
    }

    protected void ButtonSave_Click(object sender, EventArgs e)
    {
        DateTime dttmp;
        DateTime? planfinishTime = null;
        if (DateTime.TryParse(TextBoxPlanFinishTime.Text, out dttmp))
        {
            planfinishTime = dttmp;
        }
        int? number = null;
        int iTemp;
        if (int.TryParse(TextBoxCount.Text, out iTemp))
        {
            number = iTemp;
        }

        JobBiz.UpdateJob(jobId, TextBoxSummary.Text.Trim(), planfinishTime, number, DropDownListUnit.SelectedValue, TextBoxCustomer.Text.Trim(), TextBoxDesc.Text, User.Identity.Name);
        Response.Redirect("job.aspx?J=" + jobId);
    }

    protected void DropDownListState_SelectedIndexChanged(object sender, EventArgs e)
    {
        JobBiz.UpdateState_Force(jobId, User.Identity.Name, DropDownListState.SelectedValue);
    }
}
